// src/App.jsx
import React, { useEffect } from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate, useLocation } from 'react-router-dom';
import { ConfigProvider, TabBar } from 'antd-mobile';
import zhCN from 'antd-mobile/es/locales/zh-CN';
import { AnimatePresence } from 'framer-motion';
import { 
  AppOutline, 
  MessageOutline, 
  UnorderedListOutline, 
  UserOutline,
  StarOutline
} from 'antd-mobile-icons';

// Pages
import Login from './pages/Login';
import Register from './pages/Register';
import Jian from './pages/Jian';
import Tong from './pages/Tong';
import Si from './pages/Si';
import Fen from './pages/Fen';
import Wu from './pages/Wu';
import Zhending from './pages/Zhending';
import FavoriteList from './pages/FavoriteList';
import Backpack from './pages/Backpack';
import EditProfile from './pages/EditProfile';

// Components
import AppLayout from './components/AppLayout';
import PrivateRoute from './components/PrivateRoute';

// Store
import { useAuthStore } from './store/authStore';

const tabs = [
  { key: 'jian', title: '兼收', icon: <AppOutline /> },
  { key: 'tong', title: '通感', icon: <MessageOutline /> },
  { key: 'si', title: '朝闻', icon: <UnorderedListOutline /> },
  { key: 'zhending', title: '征鼎', icon: <StarOutline /> },
  // { key: 'fen', title: '分野', icon: <StarOutline /> },
  { key: 'wu', title: '吾属', icon: <UserOutline /> },
];

// TabBar 包装组件
const TabBarWrapper = () => {
  const location = useLocation();
  const { pathname } = location;

  // 只在主路由下显示 TabBar
  const shouldShowTabBar = !pathname.includes('/login') && !pathname.includes('/register');

  if (!shouldShowTabBar) return null;

  return (
    <div className="fixed bottom-0 left-0 right-0 h-[0.45rem] bg-white border-t border-gray-200 z-[9999] mobile-safe-area">
      <TabBar 
        activeKey={pathname.replace('/', '') || 'jian'}
        onChange={(key) => {
          window.location.href = `/${key}`;
        }}
        style={{
          '--adm-color-primary': '#1677ff',
          '--adm-font-size-main': '0.18rem',
          '--adm-font-size-1': '0.18rem',
          '--adm-font-size-2': '0.16rem',
          '--adm-font-size-3': '0.14rem',
          '--adm-font-size-4': '0.12rem',
          '--adm-font-size-5': '0.1rem',
          '--adm-font-size-6': '0.08rem',
          '--adm-font-size-7': '0.06rem',
          '--adm-font-size-8': '0.04rem',
          '--adm-font-size-9': '0.02rem',
          '--adm-font-size-10': '0.01rem',
        }}
      >
        {tabs.map(item => (
          <TabBar.Item 
            key={item.key} 
            icon={item.icon} 
            title={item.title}
            style={{
              fontSize: '0.18rem',
              padding: '0.04rem 0',
            }}
          />
        ))}
      </TabBar>
    </div>
  );
};

// 滚动控制组件
const ScrollController = () => {
  const location = useLocation();
  
  useEffect(() => {
    const scrollablePages = ['/fen', '/zhending', '/favorites', '/wu', '/backpack'];
    const isScrollablePage = scrollablePages.includes(location.pathname);
    
    // 根据页面类型设置body样式
    if (isScrollablePage) {
      document.body.style.overflow = 'auto';
      document.documentElement.style.overflow = 'auto';
    } else {
      document.body.style.overflow = 'hidden';
      document.documentElement.style.overflow = 'hidden';
    }
    
    return () => {
      // 清理时恢复默认状态
      document.body.style.overflow = 'hidden';
      document.documentElement.style.overflow = 'hidden';
    };
  }, [location.pathname]);
  
  return null;
};

function App() {
  const { checkAuth } = useAuthStore();

  useEffect(() => {
    checkAuth();
    
    // 注册 Service Worker
    if ('serviceWorker' in navigator && process.env.NODE_ENV === 'production') {
      window.addEventListener('load', () => {
        navigator.serviceWorker.register('/sw.js', { scope: '/' })
          .then(registration => {
            console.log('ServiceWorker registration successful');
          })
          .catch(error => {
            console.error('ServiceWorker registration failed:', error);
          });
      });
    }

    // 防止页面滚动，但允许特定页面滚动
    const preventScroll = (e) => {
      const allowedPaths = ['/fen', '/zhending', '/favorites', '/wu', '/backpack','/register'];
      if (!allowedPaths.includes(window.location.pathname)) {
        e.preventDefault();
      }
    };
    
    
    document.addEventListener('touchmove', preventScroll, { passive: false });
    
    return () => {
      document.removeEventListener('touchmove', preventScroll);
    };
  }, [checkAuth]);

  return (
    <ConfigProvider locale={zhCN}>
      <div className="mobile-container mobile-no-zoom">
        <Router>
          <ScrollController />
          <AnimatePresence mode="wait">
            <Routes>
              <Route path="/login" element={<Login />} />
              <Route path="/register" element={<Register />} />
              <Route path="/edit-profile" element={<PrivateRoute><EditProfile /></PrivateRoute>} />
              <Route path="/" element={<PrivateRoute><AppLayout /></PrivateRoute>}>
                <Route index element={<Navigate to="/jian" replace />} />
                <Route path="jian" element={<Jian />} />
                <Route path="tong" element={<Tong />} />
                <Route path="si" element={<Si />} />
                <Route path="fen" element={<Fen />} />
                <Route path="wu" element={<Wu />} />
                <Route path="zhending" element={<Zhending />} />
                <Route path="favorites" element={<FavoriteList />} />
                <Route path="backpack" element={<Backpack />} />
              </Route>
              <Route path="*" element={<Navigate to="/" replace />} />
            </Routes>
          </AnimatePresence>
          <TabBarWrapper />
        </Router>
      </div>
    </ConfigProvider>
  );
}

export default App;
